package com.srwl.mytx.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.util.Log;

import androidx.annotation.Nullable;

import com.srwl.mytx.MyApplication;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by dahai2070 on 2018/3/23 0023.
 */

public class IMThumbnailUtils {
    public static Bitmap compressFileAndRotateToBitmapThumb(String filePath, int width, int height, int degree, String savePath, boolean writeCompressedBitmapBackToFile, boolean saveToSavePath) {
        Bitmap bm = compressFileToBitmapThumbAndRotate(filePath, width, height, savePath, writeCompressedBitmapBackToFile, saveToSavePath, degree);
        return bm;
    }

    private static Bitmap compressFileToBitmapThumbAndRotate(String filePath, int width, int height, String savePath, boolean writeCompressedBitmapBackToFile, boolean savePicToSavePath, int degree) {
        if(null == filePath) {
            return null;
        } else {
            int targetSize = Math.min(width, height);
            int maxPixels = width * height;
            File file = new File(filePath);
            if(!file.exists()) {
                return null;
            } else {
                FileInputStream fis = null;
                FileDescriptor fd = null;

                try {
                    fis = new FileInputStream(file);
                    fd = fis.getFD();
                } catch (Exception var32) {
                    var32.printStackTrace();
                    return null;
                }

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 1;
                options.inJustDecodeBounds = true;

                try {
                    BitmapFactory.decodeFileDescriptor(fd, (Rect)null, options);
                } catch (Exception var30) {
                    var30.printStackTrace();

                    try {
                        fis.close();
                    } catch (IOException var23) {
                        var23.printStackTrace();
                    }

                    return null;
                } catch (Throwable var31) {
                    var31.printStackTrace();

                    try {
                        fis.close();
                    } catch (IOException var24) {
                        var24.printStackTrace();
                    }

                    return null;
                }

                if(!options.mCancel && options.outWidth != -1 && options.outHeight != -1) {
                    int sampleSize = computeSampleSize(options, targetSize, maxPixels);
                    int maxSample;
                    if(!writeCompressedBitmapBackToFile) {
                        sampleSize *= 2;
                        maxSample = Math.max(sampleSize, 32);
                    } else {
                        maxSample = Math.max(sampleSize, 20);
                    }

                    options.inJustDecodeBounds = false;
                    options.inDither = false;
                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

                    for(int index = sampleSize; index <= maxSample; ++index) {
                        try {
                            options.inSampleSize = index;
                            Bitmap bm = BitmapFactory.decodeFileDescriptor(fd, (Rect)null, options);
                            if(null != bm) {
                                int currentWidth = bm.getWidth();
                                int currentHeight = bm.getHeight();
                                int currentLong;
                                int currentShort;
                                if(currentWidth > currentHeight) {
                                    currentLong = currentWidth;
                                    currentShort = currentHeight;
                                } else {
                                    currentLong = currentHeight;
                                    currentShort = currentHeight;
                                }

                                if(currentLong <= 1280 && currentShort <= 960) {
                                    fis.close();
                                    Bitmap b2;
                                    if(!savePicToSavePath) {
                                        if(bm == null) {
                                            return null;
                                        }

                                        b2 = rotateBitmap(bm, degree);
                                        if(b2 == null) {
                                            return bm;
                                        }

                                        if(bm != b2) {
                                            bm.recycle();
                                            bm = null;
                                        }

                                        return b2;
                                    }

                                    if(bm == null) {
                                        return null;
                                    }

                                    FileUtils.deleteFile(new File(savePath));
                                    b2 = rotateBitmap(bm, degree);
                                    if(b2 != null && b2 != bm) {
                                        Bitmap temp = bm;
                                        bm = b2;
                                        temp.recycle();
                                    }

                                    if(writeCompressedBitmapBackToFile) {
                                        IMFileTools.writeBitmap(savePath, bm, 50);
                                        bm.recycle();
                                        bm = null;
                                        return IMFileTools.readBitmap(savePath);
                                    }

                                    //图片复制
                                    FileUtils.copyFileFast(new File(filePath), new File(savePath));
                                    return bm;
                                }

                                bm.recycle();
                                bm = null;
                            }
                        } catch (OutOfMemoryError var26) {
                            var26.printStackTrace();
                        } catch (Exception var27) {
                            var27.printStackTrace();
                        } catch (Throwable var28) {
                            var28.printStackTrace();
                        }
                    }

                    try {
                        fis.close();
                    } catch (IOException var25) {
                        var25.printStackTrace();
                    }

                    return null;
                } else {
                    try {
                        fis.close();
                    } catch (IOException var29) {
                        var29.printStackTrace();
                    }

                    return null;
                }
            }
        }
    }

    private static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
        int roundedSize;
        if(initialSize <= 8) {
            for(roundedSize = 1; roundedSize < initialSize; roundedSize <<= 1) {
                ;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }

        return roundedSize;
    }
    private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        double w = (double)options.outWidth;
        double h = (double)options.outHeight;
        int lowerBound = maxNumOfPixels == -1?1:(int)Math.ceil(Math.sqrt(w * h / (double)maxNumOfPixels));
        int upperBound = minSideLength == -1?128:(int)Math.min(Math.floor(w / (double)minSideLength), Math.floor(h / (double)minSideLength));
        return upperBound < lowerBound?lowerBound:(maxNumOfPixels == -1 && minSideLength == -1?1:(minSideLength == -1?lowerBound:upperBound));
    }

    /**
     * 选择图片
     * @param b
     * @param degrees
     * @return
     */
    public static Bitmap rotateBitmap(Bitmap b, int degrees) {
        if(degrees != 0 && b != null) {
            Matrix m = new Matrix();
            m.setRotate((float)degrees, (float)(b.getWidth() / 2), (float)(b.getHeight() / 2));

            try {
                Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true);
                return b2;
            } catch (Exception var4) {

                    Log.d("IMThumbnail", "rotateBitmap; Exception: " + var4.toString());

            } catch (Throwable var5) {

                    Log.d("IMThumbnail", "rotateBitmap; Exception: " + var5.toString());

            }
        }

        return null;
    }
    public static int[] getResizedDimensionOfThumbnail(int actualWidth, int actualHeight, int mMinWidth, int mMaxHeight) {
        int[] resizedResults = new int[4];
        ImageMsgPacker imageMsgPacker = new ImageMsgPacker(MyApplication.getInstance());
        int DEFAULT_WIDTH = imageMsgPacker.getDefaultWidth();
        int DEFAULT_HEIGHT = imageMsgPacker.getDefaultHeight();
        if(actualWidth > 0 && actualHeight > 0) {
            if(actualWidth <= actualHeight) {
                double ratio;
                int tmpHeight;
                if(actualHeight > mMaxHeight) {
                    ratio = (double)actualHeight / (double)mMaxHeight;
                    tmpHeight = (int)((double)actualWidth / ratio);
                    if(tmpHeight > mMinWidth) {
                        resizedResults[0] = tmpHeight;
                        resizedResults[1] = mMaxHeight;
                        resizedResults[2] = actualWidth;
                        resizedResults[3] = actualHeight;
                    } else {
                        ratio = (double)mMinWidth / (double)actualWidth;
                         tmpHeight = (int)((double)actualHeight * ratio);
                        if(tmpHeight > mMaxHeight) {
                            resizedResults[0] = mMinWidth;
                            resizedResults[1] = mMaxHeight;
                            resizedResults[2] = actualWidth;
                            resizedResults[3] = (int)((double)actualWidth * (double)mMaxHeight / (double)mMinWidth);
                        } else {
                            resizedResults[0] = mMinWidth;
                            resizedResults[1] = tmpHeight;
                            resizedResults[2] = actualWidth;
                            resizedResults[3] = actualHeight;
                        }
                    }
                } else if(actualWidth < mMinWidth) {
                    ratio = (double)mMinWidth / (double)actualWidth;
                    tmpHeight = (int)((double)actualHeight * ratio);
                    if(tmpHeight > mMaxHeight) {
                        resizedResults[0] = mMinWidth;
                        resizedResults[1] = mMaxHeight;
                        resizedResults[2] = actualWidth;
                        resizedResults[3] = (int)((double)actualWidth * (double)mMaxHeight / (double)mMinWidth);
                    } else {
                        resizedResults[0] = mMinWidth;
                        resizedResults[1] = tmpHeight;
                        resizedResults[2] = actualWidth;
                        resizedResults[3] = actualHeight;
                    }
                } else {
                    resizedResults[0] = actualWidth;
                    resizedResults[1] = actualHeight;
                    resizedResults[2] = actualWidth;
                    resizedResults[3] = actualHeight;
                }
            } else {
                int[] results = getResizedDimensionOfThumbnail(actualHeight, actualWidth, mMinWidth, mMaxHeight);
                resizedResults[0] = results[1];
                resizedResults[1] = results[0];
                resizedResults[2] = results[3];
                resizedResults[3] = results[2];
            }

            return resizedResults;
        } else {
            resizedResults[0] = DEFAULT_WIDTH;
            resizedResults[1] = DEFAULT_HEIGHT;
            resizedResults[2] = DEFAULT_WIDTH;
            resizedResults[3] = DEFAULT_HEIGHT;
            return resizedResults;
        }
    }
    public static Bitmap getCropAndScaledBitmap(Bitmap oriBitmap, int desiredWidth, int desiredHeight, int resizedWidth, int resizedHeight, boolean recycle) {
        if(oriBitmap == null) {
            return null;
        } else {
            Bitmap cropBitmap = null;
            int width = oriBitmap.getWidth();
            int height = oriBitmap.getHeight();
            resizedWidth = Math.min(resizedWidth, width);
            resizedHeight = Math.min(resizedHeight, height);
            if(width == resizedWidth && height == resizedHeight) {
                cropBitmap = oriBitmap;
            } else {
                int x = Math.max((width - resizedWidth) / 2, 0);
                int y = Math.max((height - resizedHeight) / 2, 0);
                cropBitmap = Bitmap.createBitmap(oriBitmap, x, y, resizedWidth, resizedHeight);
                if(cropBitmap != oriBitmap && recycle) {
                    oriBitmap.recycle();
                }
            }

            return scaleBitmap(desiredWidth, desiredHeight, recycle, cropBitmap);
        }
    }

    @Nullable
    public static Bitmap scaleBitmap(int desiredWidth, int desiredHeight, boolean recycle, Bitmap sourceBitmap) {
        Bitmap scalebBitmap = null;
        if(sourceBitmap == null ||sourceBitmap.getWidth()<desiredWidth||sourceBitmap.getHeight()<desiredHeight|| sourceBitmap.getWidth() == desiredWidth && sourceBitmap.getHeight() == desiredHeight) {
            scalebBitmap = sourceBitmap;
        } else {
            scalebBitmap = Bitmap.createScaledBitmap(sourceBitmap, desiredWidth, desiredHeight, true);
            if(sourceBitmap != scalebBitmap && recycle) {
                sourceBitmap.recycle();
            }
        }

        return scalebBitmap;
    }

    static int findBestSampleSize(int actualWidth, int actualHeight, int desiredWidth, int desiredHeight) {
        double wr = (double)actualWidth / (double)desiredWidth;
        double hr = (double)actualHeight / (double)desiredHeight;
        double ratio = Math.min(wr, hr);

        float n;
        for(n = 1.0F; (double)(n * 2.0F) <= ratio; n *= 2.0F) {
            ;
        }

        return (int)n;
    }

    public static float getScale(int originalWidth, int originalHeight, Context context) {
        float density = context.getResources().getDisplayMetrics().density;
        float maxHeight = 150 * density;
        float maxWidth = maxHeight;
        float scale;
        if (originalHeight > originalWidth) {
            if (originalHeight > maxHeight) {
                scale = maxHeight / originalHeight;
            } else {
                scale = 1f;
            }
        } else {
            if (originalWidth > maxWidth) {
                scale = maxWidth / originalWidth;
            } else {
                scale = 1f;
            }
        }
        return scale;
    }
}
